package com.oh.core.entity;

import com.oh.core.common.constant.ConfigConst;
import com.oh.core.common.utils.MessageUtils;

/**
 * 报文体
 */
public class MessageEntity extends HeadInfo{
    private byte [] body;

    private HeadInfo headInfo;

    /**
     * 消息实体
     * @param command 指令
     * @param magic 魔数
     * 报文长度
     * @param body 报文体
     */
    public MessageEntity(byte command, int magic, byte [] body){
        int length = body.length;
        headInfo = new HeadInfo(command, magic, length);
        this.command = command;
        this.magic = magic;
        this.length = length;
        this.body = body;
    }

    /**
     * 消息实体
     * @param command 指令
     * @param body 消息
     */
    public MessageEntity(byte command, byte [] body){
        this.length = body.length;
        this.magic = ConfigConst.MAGIC_NUMBER;
        headInfo = new HeadInfo(command, magic, length);
        this.command = command;
        this.body = body;
    }
    /**
     * 封装消息实体
     * @param msg 这条消息
     */
    public MessageEntity(byte [] msg){
        try {
            HeadInfo headInfo = MessageUtils.getHead(msg);
            // 指令
            this.command = headInfo.getCommand();
            // 魔数 校验码
            this.magic = headInfo.getMagic();
            // 报文长度
            this.length = headInfo.getLength();
            // 消息头
            this.headInfo = headInfo;
            // 消息体
            this.body = MessageUtils.getBody(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setBody(byte [] body){
        this.body = body;
        this.length = body.length;
        this.headInfo.setLength(this.length);
    }

    public byte [] getBody(){
        return this.body;
    }

    public void setHeadInfo(HeadInfo headInfo){
        this.headInfo = headInfo;
    }

    public HeadInfo getHeadInfo(){
        return this.headInfo;
    }

    /**
     * 将消息实体转成报文
     * @return
     */
    public byte [] toMsgBytes(){
        byte [] bytes = null;
        try {
            bytes = MessageUtils.splicingMsg(headInfo.getCommand(), headInfo.getMagic(), this.body);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return bytes;
    }

    @Override
    public String toString(){
        return "MessageEntity [command=" + command + ", magic=" + magic + ", length=" + length + ", body=" + new String(body) + "]";
    }
}
